#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <arpa/inet.h>
#include "error.hpp"
#include <strings.h>
#include <string.h>
#include <functional>
#include <unistd.h>
#include"log.hpp"
#include"ThreadPool v4.hpp"
namespace server
{
    const int backlog = 12;
    using func_t = std::function<std::string(std::string)>;
    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port)
            : func_(func), port_(port)
        {
            ;
        }
        ~TcpServer()
        {
            ;
        }
        void InitServer()
        {
            // 1 创建套接字
            listensocket_ = socket(AF_INET, SOCK_STREAM, 0);
            if (listensocket_ < 0)
            {
                lg_(ErrorLevel::Fatal,"socket err");
                // std::cout << "socket err" << std::endl;
                exit(SOCKET_ERR);
            }
            lg_(ErrorLevel::Debug,"socket success");
            // std::cout << "socket success" << std::endl;

            // 2 绑定端口号和ip地址
            struct sockaddr_in sock; // 头文件<netinet/in.h>
            bzero(&sock, sizeof(sock));
            sock.sin_addr.s_addr = INADDR_ANY; // 设置ip地址 表示所有的ip的地址
            sock.sin_port = htons(port_);
            sock.sin_family = AF_INET;
            if (bind(listensocket_, (sockaddr *)(&sock), sizeof(sock)) < 0)
            {
                lg_(ErrorLevel::Fatal,"bind err");
                // std::cout << "bind error " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            lg_(ErrorLevel::Debug,"bind success");
            // std::cout << "bind success" << std::endl;
            // 3 开始监听
            if (listen(listensocket_, backlog)) // 返回0,监听成功
            {
                lg_(ErrorLevel::Fatal,"listen err");
                // std::cout << "listen error " << strerror(errno) << std::endl;
                exit(LISTEN_ERR);
            }
            lg_(ErrorLevel::Debug,"listen success");
        }
        void start()
        {
            while (true)
            {
                // 获取链接
                struct sockaddr_in sock; // 头文件<netinet/in.h>
                bzero(&sock, sizeof(sock));
                socklen_t len = sizeof(sock);
                int socket = accept(listensocket_, (sockaddr *)&sock, &len); // 不保存吗
                if (socket < 0)
                {
                    lg_(ErrorLevel::Info,"accept err");
                    // std::cout << "accept err" << std::endl;
                    exit(SOCKET_ERR);
                }
                std::cout << "accept success" << std::endl;
                // 开始发消息,此时我们不能让主线程去发消息,不然就无法链接其它的客户端了
                std::string clientip = inet_ntoa(sock.sin_addr);
                u_int16_t clientport = ntohs(sock.sin_port);

                Task t(socket,clientip,clientport,std::bind(&TcpServer::server,this,
                std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
                threadPool<Task>::getthreadPool()->push(t);//push一个任务入队列
            }
        }
        void server(int sock, std::string ip, uint16_t port)
        {
            pthread_detach(pthread_self());//分离线程
            char buffer[1024] = {0};

            int n = read(sock, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string ret = func_(buffer);
                lg_(ErrorLevel::Debug,"%s->%s#%s",ip.c_str(),to_string(port).c_str(),ret.c_str());
                // 写回给客户端
                write(sock, ret.c_str(), ret.size());
            }
            else if (n == 0)
            {
                close(sock);
                lg_(ErrorLevel::Debug,"%s->%s#断开连接",ip.c_str(),to_string(port).c_str());
                // std::cout << name << " 断开连接" << std::endl;
            }
            else
            {
                close(sock);
                lg_(ErrorLevel::Fatal,"server read err");
                // std::cout << "server read err" << strerror(errno) << std::endl;
                // exit(READ_ERR);
            }

        }

    private:
        int listensocket_;
        func_t func_;
        Log lg_;
        // int socket_;
        int port_;
    };
};